//
//  RelationListViewController.m
//  parent
//
//  Created by ci123 on 15/7/13.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "RelationListViewController.h"
#import "UserDao.h"
#import "BabyInfo.h"
#import "UserInfo.h"
#import "JsonUtil.h"
#import "PopUIManager.h"
#import "NetWorkManager.h"
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "AddMemberViewController.h"

@interface RelationListViewController ()

@end

@implementation RelationListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    BabyInfo *info = [[UserDao getInstance]getCurrentBaby];
    UserInfo *user_info = [[UserDao getInstance]getUserInfo];
    NSString *child_id = [NSString stringWithFormat:@"%ld", (long)info.cid];
    NSString *user_id = [NSString stringWithFormat:@"%ld", (long)user_info.userId];
    NSString *token = user_info.access_token;
    NSLog(@"%@  %@  %@",child_id,user_id,token);
    
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden=NO;
    
    self.title = [NSString stringWithFormat:@"%@的家人",[[UserDao getInstance]getCurrentBaby].cname];
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    
    [self.navigationController.navigationBar setBarTintColor:UIColorMake(252,74,74)];
    self.navigationController.navigationBar.shadowImage = nil;
    self.navigationController.navigationBar.translucent = NO;
    [self.view setBackgroundColor:DefaultViewColor];
    
    //根据当前宝宝获取他的所有家人
    [self requestServerBabyId:child_id userId:user_id accessToken:token];
}



- (void)initList:(NSDictionary *)mDict {
    NSLog(@"mDict:%@",mDict);
    NSString *avatar_header = [mDict valueForKey:@"avatar_header"];
    NSArray *parent_list = [mDict valueForKey:@"parent_info"];
    NSArray *role_data = [NSArray arrayWithObjects:@"宝宝",@"爸爸",@"妈妈",@"爷爷",@"奶奶",@"外公",@"外婆",@"其他", nil];
    
    NSInteger padding = 10;
    NSInteger center_gap = 6;
    CGFloat view_width = (APP_SCREEN_WIDTH -  padding * 2 - center_gap) / 2;
    
    CGFloat avatar_width = view_width * 0.45;
    CGFloat avatar_startX = (view_width - avatar_width) / 2;
    CGFloat avatar_startY = view_width *0.18;
    
    CGFloat view_bottom = 0;
    CGFloat view_left = 0;
    
    NSInteger current_index = 0;
    
    for (NSDictionary *parent_dict in parent_list) {
        NSString *avatar = [parent_dict valueForKey:@"avatar"];
        if (avatar == nil || [avatar isEqual:[NSNull null]]) {
            avatar = @"null";
        }else{
            avatar = [avatar_header stringByAppendingString:avatar];
        }
        NSInteger role_type = [[parent_dict valueForKey:@"frole"]integerValue];
 
        UIView *white_view = [[UIView alloc]initWithFrame:CGRectMake(view_left + padding, view_bottom + padding, view_width, view_width)];
        white_view.layer.borderColor = UIColorMake(230, 230, 230).CGColor;
        white_view.layer.borderWidth = 1;
        white_view.backgroundColor = [UIColor whiteColor];
        [_scroll_view addSubview:white_view];
        
        UIImageView *avatar_img = [[UIImageView alloc]initWithFrame:CGRectMake(avatar_startX, avatar_startY, avatar_width, avatar_width)];
        avatar_img.layer.masksToBounds = YES;
        avatar_img.layer.cornerRadius = avatar_width/2;
        [avatar_img sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"default_circle_icon"]];
        [white_view addSubview:avatar_img];
        
        UILabel *name_label = [[UILabel alloc]init];
        name_label.text = [role_data objectAtIndex:role_type];
        [name_label sizeToFit];
        name_label.center = CGPointMake(view_width / 2, avatar_img.bottom + 20);
        [white_view addSubview:name_label];
        current_index++;
        _scroll_view.contentSize = CGSizeMake(APP_SCREEN_WIDTH, white_view.bottom + padding);
        if (current_index%2 == 1) {  //右侧框
            view_left = view_width + center_gap;
        }else{  //左侧框
            view_bottom = white_view.bottom;
            view_left = 0;
        }
    }
    
    UIView *white_view = [[UIView alloc]initWithFrame:CGRectMake(view_left + padding, view_bottom + padding, view_width, view_width)];
    white_view.layer.borderColor = UIColorMake(230, 230, 230).CGColor;
    white_view.layer.borderWidth = 1;
    white_view.backgroundColor = [UIColor whiteColor];
    [_scroll_view addSubview:white_view];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(inviteButton:)];
    [white_view addGestureRecognizer:tap];
    
    UIImageView *avatar_img = [[UIImageView alloc]initWithFrame:CGRectMake(avatar_startX, avatar_startY, avatar_width, avatar_width)];
    avatar_img.layer.masksToBounds = YES;
    [avatar_img setImage:[UIImage imageNamed:@"invite_default"]];
    [white_view addSubview:avatar_img];
    
    UILabel *name_label = [[UILabel alloc]init];
    name_label.text = @"邀请亲人";
    name_label.textColor = [UIColor grayColor];
    [name_label sizeToFit];
    name_label.center = CGPointMake(view_width / 2, avatar_img.bottom + 20);
    [white_view addSubview:name_label];

    _scroll_view.contentSize = CGSizeMake(APP_SCREEN_WIDTH, white_view.bottom + padding);
}
- (IBAction)inviteButton:(id)sender {
    AddMemberViewController *amvc = [[AddMemberViewController alloc]init];
    [self.navigationController pushViewController:amvc animated:YES];
    
}

- (void)requestServerBabyId:(NSString *)child_id userId:(NSString *)user_id accessToken:(NSString *)token{
    NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:user_id, @"uid",child_id,@"child_id",token,@"token",nil]];
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:@"BABY_GET_PARENTS" data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) { //连接失败
            debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
            NSLog(@"服务器返回StateCode:%ld", (long)responseCode);
            
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                NSLog(@"数据字典: %@", dict);
                
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    //登录失败，弹窗提示
                    NSString *ret_msg;
                    switch ([[dict objectForKey:@"retCode"] integerValue]) {
                        case 1:{
                            ret_msg = @"Success";
                            break;
                        }
                        case 10005:{
                            ret_msg= @"没有查询到同一个家族的孩子亲人";
                            break;
                        }default:{
                            ret_msg= @"未知错误";
                            break;
                        }
                    }
                    if (![ret_msg isEqual:@"Success"]) {
                        [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                    }else{
                        [self initList:dict];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
